import fetch from 'node-fetch'
import fs from 'fs'
import path from 'path'

// Power BI API配置
const POWERBI_API_URL = 'https://api.powerbi.com/beta/e96fa72b-c8d6-4957-96bd-c7f8dc30cc88/datasets/31fb02b8-3e95-4bec-b9b2-5af9c0d67aa0/rows?experience=power-bi&key=28Ri5RxnC5wvZFax5umuUDI2FZi6LxZ6q1bZPLqtfNfSXkLIuxqvge6bkETamwjdYIo%2F0EP8sgoAVzi55wI2Dw%3D%3D'

// 获取应用版本
function getAppVersion() {
  try {
    const packageJsonPath = path.join(process.cwd(), 'package.json')
    const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
    return packageJson.version || '0.1.0'
  } catch (error) {
    console.error('获取应用版本失败:', error)
    return '0.1.0'
  }
}

/**
 * 发送文件处理统计数据到Power BI
 * @param {Object} params - 统计参数
 * @param {string} params.userName - 登录的用户名
 * @param {string} params.userLocation - 用户的location
 * @param {string} params.fileName - 处理的文件名
 * @param {string} params.sgsToken - 用户的SGS Token（可选，用于获取最新的location信息）
 */
export async function sendFileProcessingStats(params) {
  try {
    const { userName, userLocation, fileName, sgsToken, labBuInfo } = params
    
    // console.log('=== PowerBI统计调试信息 ===')
    // console.log('接收到的参数:', { 
    //   userName, 
    //   userLocation, 
    //   fileName, 
    //   sgsToken: sgsToken ? '存在' : '不存在',
    //   labBuInfo: labBuInfo ? '存在' : '不存在'
    // })
    
    // 如果提供了labBuInfo，直接使用；否则尝试重新获取
    let finalUserLocation = userLocation
    if (userLocation === 'Unknown' || !userLocation) {
      if (labBuInfo && labBuInfo.locationName) {
        finalUserLocation = labBuInfo.locationName
        console.log('从传入的labBuInfo中获取到locationName:', finalUserLocation)
      } else if (sgsToken) {
        try {
          console.log('userLocation为Unknown，尝试通过getUserLabBuInfo重新获取...')
          const { getUserLabBuInfo } = await import('../models/gpo-api.js')
          const apiLabBuInfo = await getUserLabBuInfo(sgsToken)
          console.log('getUserLabBuInfo返回的完整数据:', JSON.stringify(apiLabBuInfo, null, 2))
          if (apiLabBuInfo && apiLabBuInfo.locationName) {
            finalUserLocation = apiLabBuInfo.locationName
            console.log('通过getUserLabBuInfo重新获取到locationName:', finalUserLocation)
          } else {
            console.warn('getUserLabBuInfo返回的数据中没有locationName字段')
          }
        } catch (error) {
          console.warn('重新获取location信息失败:', error)
        }
      }
    }
    
    console.log('最终使用的userLocation:', finalUserLocation)
    
    // 构建请求数据
    const requestData = {
      user_name: userName || 'Unknown',
      user_location: finalUserLocation || 'Unknown',
      rpa_id: "144",
      rpa_name: "TRF to GPO",
      rpa_version: getAppVersion(),
      occurrence: new Date().toLocaleString('en-US', {
                weekday: 'short',
                day: '2-digit',
                month: 'short',
                year: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }),
      info: "TRF识别并将字段写入GPO",
      extra: fileName || 'Unknown'
    }
    
    // console.log('准备发送Power BI统计数据:', requestData)
    
    // 发送POST请求到Power BI API
    const response = await fetch(POWERBI_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      // Power BI Push API 需要 { rows: [...] } 格式
      body: JSON.stringify({ rows: [requestData] })
    })
    
    if (response.ok) {
      const responseData = await response.text()
      // console.log('Power BI统计数据发送成功，状态:', response.status)
      return { 
        success: true, 
        status: response.status,
        requestData: requestData,
        responseData: responseData || 'Success'
      }
    } else {
      const errorText = await response.text()
      console.error('Power BI API响应错误:', response.status, errorText)
      return { 
        success: false, 
        status: response.status,
        requestData: requestData,
        error: {
          message: `HTTP ${response.status}: ${response.statusText}`,
          details: errorText
        }
      }
    }
    
  } catch (error) {
    console.error('发送Power BI统计数据失败:', error)
    return { 
      success: false, 
      requestData: params,
      error: {
        message: 'Failed to send statistics',
        details: error.message
      }
    }
  }
}

/**
 * 批量发送文件处理统计数据
 * @param {Array} fileList - 文件列表
 * @param {Object} userInfo - 用户信息
 */
export async function sendBatchFileProcessingStats(fileList, userInfo) {
  const results = []
  
  for (const file of fileList) {
    const result = await sendFileProcessingStats({
      userName: userInfo.userName,
      userLocation: userInfo.userLocation,
      fileName: file.originalName || file.fileName
    })
    
    results.push({
      fileName: file.originalName || file.fileName,
      result
    })
    
    // 添加小延迟避免API限制
    await new Promise(resolve => setTimeout(resolve, 100))
  }
  
  return results
}